package com.apestech.framework.sql.table;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.sql.condition.ConditionMap;
import com.apestech.framework.sql.modul.FromList;
import com.apestech.framework.sql.modul.SqlList;
import com.apestech.framework.util.StringFuncUtil;

public class TableSql extends StringFuncUtil {
	
	private FromList fromtab;
	private ConditionMap param;
	private SqlList sqlparam=null;
	private String tabname;
	private String schema;

	public TableSql(String tabname, SqlSession session, ConditionMap param) throws Exception{
		this.schema=null;
		this.tabname=tabname;
		int pos=tabname.indexOf(".");
		if(pos>=0) {
			this.schema = tabname.substring(0, pos);
			this.tabname = tabname.substring(pos + 1, tabname.length());
		}
		if(param.getFromtab()==null) this.fromtab=new FromList(this.tabname,null, session);
		else this.fromtab=param.getFromtab();
//		if(fromtab.size()!=1){
//			throw new Exception(getMessage("TableSql_errorTableCount","表名只能有一个，实际有[({0})]个!",fromtab.size()));
//		}
		this.param=param;
		if(this.param==null){
			this.param=new ConditionMap(null);
		}
		if(this.param.getFromtab()==null) this.param.setFromtab(this.fromtab);
		if(this.param.getSqlType()==null){
			throw new Exception(getMessage("TableSql_errorTableType","表操作类型sqltype必填!"));
		}
	}

	public String getSql() throws Exception {
		switch (param.getSqlType()){
			case "select": {
				return getSelect();
			}
			case "insert": {
				return getInsert();
			}
			case "update": {
				return getUpdate();
			}
			case "delete": {
				return getDelete();
			}
		}
		return null;
	}

	public String getSelect() throws Exception {
		TableSelect select=new TableSelect(param);
		select.setSchema(schema);
		select.setoSqlCallback(param.getoSqlCallback());
		select.getTableSql();
		String s=select.getSql();
		sqlparam=select.getSqlparam();
		return s;
	}

	public String getInsert() throws Exception {
		TableInsert insert=new TableInsert(param);
		insert.setSchema(schema);
		insert.getTableSql();
		String s=insert.getSql();
		sqlparam=insert.getSqlparam();
		return s;
	}

	public String getUpdate() throws Exception {
		TableUpdate update=new TableUpdate(param);
		update.setSchema(schema);
		update.getTableSql();
		String s=update.getSql();
		sqlparam=update.getSqlparam();
		return s;
	}

	public String getDelete() throws Exception {
		TableDelete delete=new TableDelete(param);
		delete.setSchema(schema);
		delete.getTableSql();
		String s=delete.getSql();
		sqlparam=delete.getSqlparam();
		return s;
	}

	public FromList getFromtab() {
		return fromtab;
	}

	public SqlList getSqlparam() {
		return sqlparam;
	}
}
